import {saveAs} from 'file-saver'
import moment from "moment";
const XLSX = window.XLSX

const formatTableHeadValue = (
    value,
    headers = {
        'Mac': '设备号',
        'Brand': '品牌',
        'Logint': '登陆时间',
        'FirstLogint': '首次登陆',
        'From': '来源',
        'Pac': '渠道包',
        'PhoneType': '手机型号',
        'Total': '总登陆数',
    }) => {
    const m = headers
    if (m[value]) return m[value]
    return value
}

const formatValue = (key, value) => {
    // Brand: "iphone"
    // FirstLogint: 1596678929
    // From: "local"
    // Logint: 1596684278
    // Mac: "keyu"
    // Pac: ""
    // PhoneType: "12219991"
    if (key === 'Brand') {
        return value
    } else if (key === 'FirstLogint' || key === 'Logint') {
        return moment(new Date(value * 1000)).format('YYYY-MM-DD HH:mm')
    } else if (key === 'From') {
        const m = {
            'retou': '热投',
            'promotion_channel': '渠道包',
        }
        if (m[value]) {
            return m[value]
        }
        return value
    } else {
        return value
    }
}

export function downloadExl(data, fileName = '游客.xlsx', sheetName = '游客统计', headers) {

    var keys = Object.keys(data[0]);
    var firstRow = {};
    keys.forEach(function (item) {
        firstRow[item] = formatTableHeadValue(item, headers);
    });
    data.unshift(firstRow);

    var content = {};

    // 把json格式的数据转为excel的行列形式
    var sheetsData = data.map(function (item, rowIndex) {
        return keys.map(function (key, columnIndex) {
            return Object.assign({}, {
                value: rowIndex === 0 ? item[key] : formatValue(key, item[key]),
                position: (columnIndex > 25 ? getCharCol(columnIndex) : String.fromCharCode(65 + columnIndex)) + (rowIndex + 1),
            });
        });
    }).reduce(function (prev, next) {
        return prev.concat(next);
    });

    sheetsData.forEach(function (item, index) {
        content[item.position] = { v: item.value };
    });

    //设置区域,比如表格从A1到D10,SheetNames:标题，
    var coordinate = Object.keys(content);
    var workBook = {
        SheetNames: [sheetName],
        Sheets: {
            [sheetName]: Object.assign({}, content, { "!ref": coordinate[0] + ":" + coordinate[coordinate.length - 1] }),
        }
    };
    //这里的数据是用来定义导出的格式类型
    var excelData = XLSX.write(workBook, { bookType: "xlsx", bookSST: false, type: "binary" });
    var blob = new Blob([string2ArrayBuffer(excelData)], { type: "" });
    saveAs(blob, fileName);
}
//字符串转字符流
function string2ArrayBuffer(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
}
// 将指定的自然数转换为26进制表示。映射关系：[0-25] -> [A-Z]。
function getCharCol(n) {
    let temCol = "",
        s = "",
        m = 0
    while (n > 0) {
        m = n % 26 + 1
        s = String.fromCharCode(m + 64) + s
        n = (n - m) / 26
    }
    return s
}


//

//
// export function downloadExl(data, type) {
//
//     const keys = Object.keys(data[0]);
//     const firstRow = {};
//     keys.forEach(function (item) {
//         firstRow[item] = formatTableHeadValue(item);
//     });
//     data.unshift(firstRow);
//
//     const content = {};
//
//     // 把json格式的数据转为excel的行列形式
//     var sheetsData = data.map(function (item, rowIndex) {
//         return keys.map(function (key, columnIndex) {
//
//             const pos = (columnIndex > 25 ? getCharCol(columnIndex) : String.fromCharCode(65 + columnIndex)) + (rowIndex + 1)
//
//             return Object.assign({}, {
//                 value: rowIndex === 0 ? item[key] : formatValue(key, item[key]),
//                 position: pos,
//             });
//         });
//     }).reduce(function (prev, next) {
//         return prev.concat(next);
//     });
//
//     sheetsData.forEach(function (item, index) {
//         content[item.position] = { v: item.value };
//     });
//
//     //设置区域,比如表格从A1到D10,SheetNames:标题，
//     console.log(content)
//     var coordinate = Object.keys(content);
//
//     var workBook = {
//         SheetNames: ["游客统计"],
//         Sheets: {
//             "sheet1": Object.assign({}, content, { "!ref": coordinate[0] + ":" + coordinate[coordinate.length - 1] }),
//         }
//     };
//     //这里的数据是用来定义导出的格式类型
//     var excelData = XLSX.write(workBook, { bookType: "xlsx", bookSST: false, type: "binary" });
//     var blob = new Blob([string2ArrayBuffer(excelData)], { type: "" });
//     console.log(blob)
//     saveAs(blob, "游客.xlsx");
// }
// //字符串转字符流
// function string2ArrayBuffer(s) {
//     var buf = new ArrayBuffer(s.length);
//     var view = new Uint8Array(buf);
//     for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
//     return buf;
// }
// // 将指定的自然数转换为26进制表示。映射关系：[0-25] -> [A-Z]。
// function getCharCol(n) {
//     let temCol = "",
//         s = "",
//         m = 0
//     while (n > 0) {
//         m = n % 26 + 1
//         s = String.fromCharCode(m + 64) + s
//         n = (n - m) / 26
//     }
//     return s
// }